package ACWing.DataStructure.堆;
//838. 堆排序
import java.util.Scanner;

/**
 * @author :chenjie
 * @date :Created 2022/12/29 16:49
 */

/**
 * 切记这个排序只能保持最小的值在最前面不能保证数组的完全有序
 */
public class heapsort {
    static int[]h=new int[100010];
    static int size;
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int m=sc.nextInt();
        size=n;
        for (int i = 1; i <= n; i++) {
            h[i]=sc.nextInt();
        }
        for (int i = n/2; i !=0; i--) {
            down(i);
        }
//        for (int i = 1; i <= n; i++) {
//            System.out.println(h[i]);
//        }
        while (m-->0){
            System.out.print(h[1]+" ");
            h[1]=h[size];
            size--;
            down(1);
        }
    }
    public static void down(int u){//将最小值赋值到父节点向下遍历
        int t=u;
        if(u*2+1<=size&&h[u*2+1]<h[t]){
            t=u*2+1;
        }
        if(u*2<=size&&h[u*2]<h[t]){
            t=u*2;
        }
        if(t!=u){
            int temp=h[u];
            h[u]=h[t];
            h[t]=temp;
            down(t);
        }

    }
    public static void up(int u){//向上遍历与上类似不过只判断父节点与我的大小符合就换位
        while (u/2>0&&h[u/2]>h[u]){
            int temp=h[u];
            h[u]=h[u/2];
            h[u/2]=temp;
            down(u/2);
            u=u/2;
        }
    }
}
